package simpletestbed.core;


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class SimpleTestBedClient {
	private String serverName;
	
	public SimpleTestBedClient() {
		this.serverName = "localhost";
	}
	
	public SimpleTestBedClient(String serverName) {
		this.serverName = serverName;
	}

	
	public void execSendClasses(String classRemoteFolder, String localClassPath) throws IOException {
		int port = SimpleTestBedServer.TCP_PORT;
		Socket clientSocket = new Socket(serverName, port);
		DataOutputStream dos = new DataOutputStream(clientSocket.getOutputStream());
		
		// Send the command
		dos.writeUTF(SimpleTestBedServer.SENDCLASS_COMMAND);
		dos.writeBoolean(true); // this command needs to sync
		// Send the remote class folder
		dos.writeUTF(classRemoteFolder);
		// Send the java class package		
		JavaClassPackage classPackage = new JavaClassPackage();
		classPackage.loadFromLocal(localClassPath);
		byte[] packageBuf = classPackage.loadFromLocal(localClassPath);
		dos.write(packageBuf);
	}
	
	public byte[] execRun(String className, String method, boolean checkMemUsage, 
			long timeout, byte[] arg) throws IOException {
		int port = SimpleTestBedServer.TCP_PORT;
		Socket clientSocket = new Socket(serverName, port);
		DataOutputStream dos = new DataOutputStream(clientSocket.getOutputStream());
		DataInputStream dis = new DataInputStream(clientSocket.getInputStream());
		// Send the command
		dos.writeUTF(SimpleTestBedServer.RUN_COMMAND);
		dos.writeBoolean(false); // No need to sync
		// Send the start class name, method name and argument
		dos.writeUTF(className);
		dos.writeUTF(method);
		dos.writeBoolean(checkMemUsage);
		dos.writeLong(timeout);
		dos.writeInt(arg.length);
		dos.write(arg);		
		dos.flush();
		
		// Receive result
		int resultLen = dis.readInt();
		byte[] resultBuf = new byte[resultLen];
		dis.readFully(resultBuf);
		
		// Close the socket
		clientSocket.close();
		
		return resultBuf;
	}
	
	public void test1(SimpleTestBedServer server) {
		System.out.println("server runs!!!!!!!!!!");
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			SimpleTestBedClient client = new SimpleTestBedClient("localhost");
			client.execRun(SimpleTestBedClient.class.getName(), "test1", false, 100*1000, "test".getBytes());
		}catch(Exception e) {
			e.printStackTrace();
		}
	}

}
